"""
会话管理API路由
基于数据库的会话管理实现
"""

from typing import List, Optional
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session as DBSession
from src.config.database import get_db
from src.services.database_session_service import DatabaseSessionService
from src.models.session import (
    SessionCreate,
    SessionUpdate,
    SessionResponse,
    SessionInteractionCreate,
    SessionInteractionResponse,
    SessionListResponse,
    SessionHistoryResponse,
    SessionStats
)
from src.utils.error_handler import api_error_handler
from src.exceptions import SessionNotFoundError, DatabaseError

router = APIRouter(prefix="/sessions", tags=["sessions"])


@router.get("", response_model=SessionListResponse)
def list_sessions(
    active_only: bool = True,
    db: DBSession = Depends(get_db)
):
    """
    获取所有会话列表
    
    Args:
        active_only: 是否只返回活跃会话
        db: 数据库会话
        
    Returns:
        会话列表响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        if active_only:
            sessions = session_service.get_active_sessions()
        else:
            # 获取所有会话
            from src.models.session import Session as SessionModel
            all_sessions = db.query(SessionModel).order_by(SessionModel.updated_at.desc()).all()
            sessions = [session_service._session_to_response(session) for session in all_sessions]
        
        # 统计信息
        active_count = len([s for s in sessions if s.status == "active"])
        closed_count = len(sessions) - active_count
        
        return SessionListResponse(
            sessions=sessions,
            total_count=len(sessions),
            active_count=active_count,
            closed_count=closed_count
        )
    except Exception as e:
        return api_error_handler(e)


@router.post("", response_model=SessionResponse, status_code=status.HTTP_201_CREATED)
def create_session(
    session_data: SessionCreate,
    db: DBSession = Depends(get_db)
):
    """
    创建新会话
    
    Args:
        session_data: 会话创建数据
        db: 数据库会话
        
    Returns:
        创建的会话响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        session = session_service.create_session(
            name=session_data.name,
            user_id=session_data.user_id,
            metadata=session_data.metadata
        )
        return session
    except Exception as e:
        return api_error_handler(e)


@router.get("/{session_id}", response_model=SessionResponse)
def get_session(
    session_id: uuid.UUID,
    db: DBSession = Depends(get_db)
):
    """
    获取会话详情
    
    Args:
        session_id: 会话ID
        db: 数据库会话
        
    Returns:
        会话详情响应
    """
    try:
        session_service = DatabaseSessionService(db)
        session = session_service.get_session(session_id)
        return session
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.put("/{session_id}", response_model=SessionResponse)
def update_session(
    session_id: uuid.UUID,
    session_data: SessionUpdate,
    db: DBSession = Depends(get_db)
):
    """
    更新会话信息
    
    Args:
        session_id: 会话ID
        session_data: 会话更新数据
        db: 数据库会话
        
    Returns:
        更新后的会话响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        # 构建更新字段
        updates = {}
        if session_data.name is not None:
            updates["name"] = session_data.name
        if session_data.status is not None:
            updates["status"] = session_data.status
        if session_data.metadata is not None:
            updates["metadata"] = session_data.metadata
        
        session = session_service.update_session(session_id, updates)
        return session
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.delete("/{session_id}")
def delete_session(
    session_id: uuid.UUID,
    db: DBSession = Depends(get_db)
):
    """
    删除会话
    
    Args:
        session_id: 会话ID
        db: 数据库会话
        
    Returns:
        删除结果
    """
    try:
        session_service = DatabaseSessionService(db)
        
        # 先关闭会话
        session_service.close_session(session_id)
        
        # 这里可以添加物理删除逻辑，但通常建议保留历史数据
        # 目前只做软删除（关闭会话）
        
        return {"message": "会话已关闭", "session_id": str(session_id)}
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.get("/{session_id}/history", response_model=SessionHistoryResponse)
def get_session_history(
    session_id: uuid.UUID,
    limit: Optional[int] = None,
    db: DBSession = Depends(get_db)
):
    """
    获取会话历史记录
    
    Args:
        session_id: 会话ID
        limit: 限制返回的记录数
        db: 数据库会话
        
    Returns:
        会话历史响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        # 获取会话信息
        session = session_service.get_session(session_id)
        
        # 获取交互历史
        interactions = session_service.get_session_history(session_id, limit)
        
        return SessionHistoryResponse(
            session=session,
            interactions=interactions,
            total_interactions=len(interactions)
        )
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.post("/{session_id}/interactions", response_model=SessionInteractionResponse)
def add_interaction(
    session_id: uuid.UUID,
    interaction_data: SessionInteractionCreate,
    db: DBSession = Depends(get_db)
):
    """
    添加交互记录到会话
    
    Args:
        session_id: 会话ID
        interaction_data: 交互记录数据
        db: 数据库会话
        
    Returns:
        创建的交互记录响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        interaction = session_service.add_interaction(
            session_id=session_id,
            question=interaction_data.question,
            response=interaction_data.response,
            processing_time=interaction_data.processing_time,
            success=interaction_data.success,
            error_message=interaction_data.error_message,
            search_strategy=interaction_data.search_strategy,
            research_complete=interaction_data.research_complete
        )
        return interaction
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.get("/{session_id}/stats", response_model=SessionStats)
def get_session_stats(
    session_id: uuid.UUID,
    db: DBSession = Depends(get_db)
):
    """
    获取会话统计信息
    
    Args:
        session_id: 会话ID
        db: 数据库会话
        
    Returns:
        会话统计信息
    """
    try:
        session_service = DatabaseSessionService(db)
        stats = session_service.get_session_stats(session_id)
        return stats
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.post("/{session_id}/close", response_model=SessionResponse)
def close_session(
    session_id: uuid.UUID,
    db: DBSession = Depends(get_db)
):
    """
    关闭会话
    
    Args:
        session_id: 会话ID
        db: 数据库会话
        
    Returns:
        关闭后的会话响应
    """
    try:
        session_service = DatabaseSessionService(db)
        session = session_service.close_session(session_id)
        return session
    except SessionNotFoundError as e:
        return api_error_handler(e)
    except Exception as e:
        return api_error_handler(e)


@router.post("/cleanup")
def cleanup_sessions(
    max_age_days: int = 30,
    db: DBSession = Depends(get_db)
):
    """
    清理过期会话
    
    Args:
        max_age_days: 最大保留天数
        db: 数据库会话
        
    Returns:
        清理结果
    """
    try:
        session_service = DatabaseSessionService(db)
        cleaned_count = session_service.cleanup_old_sessions(max_age_days)
        return {
            "message": f"清理了 {cleaned_count} 个过期会话",
            "cleaned_count": cleaned_count
        }
    except Exception as e:
        return api_error_handler(e)

@router.get("/search", response_model=SessionListResponse)
def search_sessions(
    user_id: Optional[uuid.UUID] = None,
    keyword: Optional[str] = None,
    category: Optional[str] = None,
    tags: Optional[str] = None,
    status: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    limit: int = 100,
    offset: int = 0,
    db: DBSession = Depends(get_db)
):
    """
    搜索会话
    
    Args:
        user_id: 用户ID（可选）
        keyword: 搜索关键词（可选，用于名称搜索）
        category: 会话分类（可选）
        tags: 标签名称列表（可选，逗号分隔）
        status: 会话状态（可选）
        start_date: 开始日期（可选，格式：YYYY-MM-DD）
        end_date: 结束日期（可选，格式：YYYY-MM-DD）
        limit: 结果数量限制
        offset: 结果偏移量
        db: 数据库会话
        
    Returns:
        搜索结果列表响应
    """
    try:
        session_service = DatabaseSessionService(db)
        
        # 处理参数
        tag_list = None
        if tags:
            tag_list = [tag.strip() for tag in tags.split(",") if tag.strip()]
        
        # 处理日期参数
        start_date_obj = None
        end_date_obj = None
        if start_date:
            try:
                from datetime import datetime
                start_date_obj = datetime.strptime(start_date, "%Y-%m-%d")
            except ValueError:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="开始日期格式错误，应为YYYY-MM-DD"
                )
        
        if end_date:
            try:
                from datetime import datetime
                end_date_obj = datetime.strptime(end_date, "%Y-%m-%d")
                # 设置为当天的结束时间
                end_date_obj = end_date_obj.replace(hour=23, minute=59, second=59)
            except ValueError:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="结束日期格式错误，应为YYYY-MM-DD"
                )
        
        # 处理分类参数
        category_enum = None
        if category:
            from src.models.session import SessionCategory
            try:
                category_enum = SessionCategory[category.upper()]
            except KeyError:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"无效的分类值: {category}"
                )
        
        # 处理状态参数
        status_enum = None
        if status:
            from src.models.session import SessionStatus
            try:
                status_enum = SessionStatus[status.upper()]
            except KeyError:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"无效的状态值: {status}"
                )
        
        # 执行搜索
        sessions = session_service.search_sessions(
            user_id=user_id,
            keyword=keyword,
            category=category_enum,
            tag_names=tag_list,
            status=status_enum,
            start_date=start_date_obj,
            end_date=end_date_obj,
            limit=limit,
            offset=offset
        )
        
        # 统计信息
        active_count = len([s for s in sessions if s.status == "active"])
        closed_count = len(sessions) - active_count
        
        return SessionListResponse(
            sessions=sessions,
            total_count=len(sessions),
            active_count=active_count,
            closed_count=closed_count
        )
    except HTTPException:
        raise
    except Exception as e:
        return api_error_handler(e)